package com.lw.leetcode.binary.b;

import java.util.TreeSet;

/**
 * Created with IntelliJ IDEA.
 * 2517. 礼盒的最大甜蜜度
 *
 * @author liw
 * @version 1.0
 * @date 2022/12/26 14:33
 */
public class MaximumTastiness {

    public static void main(String[] args) {
        MaximumTastiness test = new MaximumTastiness();

        // 8
//        int[] price = {13, 5, 1, 8, 21, 2};
//        int k = 3;

        // 2
//        int[] price = {1, 3, 1};
//        int k = 2;

        // 0
        int[] price = {7, 7, 7, 7};
        int k = 2;

        int i = test.maximumTastiness(price, k);
        System.out.println(i);
    }

    public int maximumTastiness(int[] price, int k) {
        int a = 0;
        int b = Integer.MAX_VALUE;
        TreeSet<Integer> set = new TreeSet<>();
        for (int i : price) {
            a = Math.max(a, i);
            b = Math.min(b, i);
            set.add(i);
        }
        int st = 0;
        int end = (a - b) / (k - 1);
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            int count = 1;
            Integer c = set.ceiling(b + m);
            while (c != null) {
                count++;
                c = set.ceiling(c + m);
            }
            if (count >= k) {
                st = m;
            } else {
                end = m - 1;
            }
        }
        return st;
    }

}
